import _axiosHttp from "./ajax/axiosHttp";

import { Toast } from 'mint-ui';
import splitUrl from './splitUrl.js';
import store from "@/store";
import httpConfig from './httpConfig.js'
import wx from 'weixin-js-sdk';

var getVarType = {

    //1. 对象
    isObjEmpty: function (data) {
        for (var i in data) {
            return 'obj'; //如果不为空，则会执行到这一步，返回false
        }
    },

    //2. 函数
    isFunction: function (data) {
        //原生写法
        if (Object.prototype.toString.call(data) === "[object Function]") {
            //是函数，表示
            return 'function';
        }
    },

    //3. 数组
    isArray: function (data) {
        //原生写法
        if (Object.prototype.toString.call(data) === '[object Array]') {
            //是函数，表示
            return 'array';
        }
    },


    //4. 字符串
    isString: function (data) {
        //原生写法
        if (Object.prototype.toString.call(data) === '[object String]') {
            //是函数，表示
            return 'string';
        }
    }
};

function objDeepCopy(data) {
    var dataCopy = getVarType.isArray(data) == 'array' ? [] : {};
    for (var item in data) {
        dataCopy[item] = (typeof data[item] === 'object' && data[item] != null) ? objDeepCopy(data[item]) : data[item];
    }
    return dataCopy;
}

function getType(obj) {

    if (Object.prototype.toString.call(obj) === '[object Number]') {
        //数字
        return 'Number';
    }
    else if (Object.prototype.toString.call(obj) === '[object String]') {
        //字符串
        return 'String';
    }
    else if (Object.prototype.toString.call(obj) === '[object Array]') {
        //数组
        return 'Array'
    }
    else if (Object.prototype.toString.call(obj) === "[object Function]") {
        //函数
        return 'Function';
    }
    else if (Object.prototype.toString.call(obj) === "[object Boolean]") {
        //Boolean
        return 'Boolean';
    }
    else if (Object.prototype.toString.call(obj) === "[object Null]") {
        //Null
        return 'Null';
    }
    else if (Object.prototype.toString.call(obj) === "[object Object]") {
        //Object
        return 'Object';
    }
    else if (Object.prototype.toString.call(obj) === "[object Undefined]") {
        //Undefined
        return 'Undefined';
    }
}
function clone(obj) {
    var dataCopy = getType(obj) == 'Array' ? [] : {};
    for (var item in obj) {
        dataCopy[item] = typeof obj[item] === 'object' ? clone(obj[item]) : obj[item];
    }
    return dataCopy;
}
//两个对象合并，data_2复制到data_1上，目前只能合并层级为2的
function objCombine(obj_1, obj_2) {
    var d_1 = clone(obj_1),
        d_2 = clone(obj_2);

    for (var key in d_2) {
        //循环d_2，如果d_1没有这一条，直接复制过去，或d_1有这条，但d_2[key]不是对象
        if (!d_1.hasOwnProperty(key) || getType(d_2[key]) != 'Object') {
            d_1[key] = d_2[key]
        }
        else {
            //循环d_2[key]
            for (var k in d_2[key]) {
                //直接复制过去
                d_1[key][k] = d_2[key][k]
            }

        }
    }
    return d_1;
}

var utils = {

    //判断类型
    getVarType: getVarType,

    getType: getType,

    //深拷贝一个对象（对象中可以带数组）
    objCombine: objCombine,

    //深拷贝对象
    objDeepCopy: objDeepCopy,

    //替换null
    replaceNull: function (str) {
        if (str == null) {
            return "";
        } else {
            return str;
        }
    },
    //校验联系方式为手机号或者座机号 例如：0316-2312222   13011221212
    telNumberValid(tel, tip) {
        let RegExp3 = /^(0|86|17951)?(13[0-9]|15[012356789]|17[01678]|18[0-9]|14[57])[0-9]{8}$/;
        let RegExp4 = /^(0[0-9]{2,3}\-)([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/;
        if (RegExp3.test(tel) == false && RegExp4.test(tel) == false) {
            // tipAction(tip);
            Toast(tip);
            return false;
        } else {
            return true;
        }
    },
    //校验投资金额为 -- 限制输入12位非零开头的数字（限制输入整数，不输入小数）
    priceRulesValid(val, tip) {
        let RegExp1 = /^([1-9]\d{0,11})$/;
        if (RegExp1.test(val) == false) {
            // tipAction(tip);
            Toast(tip);
            return false;
        } else {
            return true;
        }
    },
    //校验表单元素
    formElValid(obj, obj1) {
        for (var key in obj) {

            if ((obj[key] == '' || obj[key] == undefined || obj[key] == null) && (obj[key] != 0)) {

                for (let key1 in obj1) {

                    if (key == key1) {

                        // tipAction(obj1[key1]);
                        Toast(obj1[key1]);
                        return false;
                    }
                }
            }
        }
        return true;
    },

    //校验表单元素(新，资产配置时添加，防止影响之前的需求，以后表单都采用此方法)
    newFormElValid(obj, obj1) {
        for (var key in obj) {
            if ((obj[key] == '' || obj[key] == undefined || obj[key] == null) && (obj[key] !== 0)) {
                for (let key1 in obj1) {
                    if (key == key1) {
                        // tipAction(obj1[key1]);

                        Toast(obj1[key1]);
                        return false;
                    }
                }
            }
        }
        return true;
    },

    //校验字符串是否为空
    checkIsEmpty(str) {
        if (!!str && str != 0) {
            return false;
        }
        return true;
    },

    //批量获取字典
    getDicData(arrDic, callback) {
        _axiosHttp.http({
            url: apiUrl.getDictionaryListByTypesApi,
            params: {
                types: arrDic
            }
        }, (res) => {
            callback(res.data.data || {});
        }, res => { })
    },
    //格式化字典值
    parseDic(value, dicData) {

        if (dicData == '' || dicData == null || dicData == undefined || value == -1) {
            return "--";
        } else {
            for (var i = 0; i < dicData.length; i++) {
                if (value == dicData[i].dicKey) {
                    return dicData[i].dicValue;
                } else if (value != dicData[i].dicKey && i == dicData.length - 1) {
                    return "--";
                }
            }
        }

    },
    //格式化字典值MUi
    parseDicArr(dicData) {
        var dicArr = [];
        for (var i = 0; i < dicData.length; i++) {
            dicArr.push({ value: dicData[i].dicKey, text: dicData[i].dicValue });
        }
        return dicArr;
    },

    //可传不同参数的格式化字典值方法
    parseDifDicArr(dicData, key, value) {
        key = !!key ? key : 'dicKey';
        value = !!value ? value : 'dicValue';

        var dicArr = [];
        for (var i = 0; i < dicData.length; i++) {
            dicArr.push({ value: dicData[i][key], text: dicData[i][value] });
        }
        return dicArr;
    },

    //只能输入整数
    NumberCheck(t) {

        //判断t的格式，如果是数字，则变为字符串
        if (typeof t == 'number') {
            t = t + '';
        }
        t = t.replace(/\D/g, '');
        if (t.length > 1 && t.substring(0, 1) == 0) {
            t = 0
        }
        return t
    },
    //数字转化
    //万-元
    toOne(num) {
        if (num) {
            var n = num * 10000;
            return n;
        } else {
            return num;
        }
    },
    //元-万
    toThousand(num) {
        if (num) {
            var n = num / 10000;
            return n;
        } else {
            return num;
        }

    },
    //给数字添加千分位的逗号
    comdify(n) {
        //n是传进来的需要添加千分位的数据，格式需要为字符串
        if (typeof n == 'number') {
            n = n + ''; //n如果为数字，转换成字符串
        }
        //添加千分位
        var re = /\d{1,3}(?=(\d{3})+$)/g;
        var n1 = n.replace(/^(\d+)((\.\d+)?)$/,
            function (s, s1, s2) {
                return s1.replace(re, "$&,") + s2;
            }
        );
        //返回处理过的字符串

        return n1;
    },
    /*
        整数数字转中文，小数不管用
        @number {Integer} 形如123的数字
        @return {String} 返回转换成的形如 一百二十三 的字符串
    */
    integerToChinese(number) {
        var a = (number + '').split(''),
            s = [],
            units = '个十百千万@#%亿^&~', // 单位
            chars = '零一二三四五六七八九', // 字符
            t = this;
        if (a.length > 12) {
            throw new Error('too big');
        } else {
            for (var i = 0, j = a.length - 1; i <= j; i++) {
                if (j == 1 || j == 5 || j == 9) { //两位数 处理特殊的 1*
                    if (i == 0) {
                        if (a[i] != '1') s.push(chars.charAt(a[i]));
                    } else {
                        s.push(chars.charAt(a[i]));
                    }
                } else {
                    s.push(chars.charAt(a[i]));
                }
                if (i != j) {
                    s.push(units.charAt(j - i));
                }
            }
        }
        //return s;
        return s.join('').replace(/零([十百千万亿@#%^&~])/g, function (m, d, b) { //优先处理 零百 零千 等
            b = units.indexOf(d);
            if (b != -1) {
                if (d == '亿') return d;
                if (d == '万') return d;
                if (a[j - b] == '0') return '零'
            }
            return '';
        }).replace(/零+/g, '零').replace(/零([万亿])/g, function (m, b) { // 零百 零千处理后 可能出现 零零相连的 再处理结尾为零的
            return b;
        }).replace(/亿[万千百]/g, '亿').replace(/[零]$/, '').replace(/[@#%^&~]/g, function (m) {
            return { '@': '十', '#': '百', '%': '千', '^': '十', '&': '百', '~': '千' }[m];
        }).replace(/([亿万])([一-九])/g, function (m, d, b, c) {
            c = units.indexOf(d);
            if (c != -1) {
                if (a[j - c] == '0') return d + '零' + b
            }
            return m;
        });
    },

    //得到26个大写英文字母，数组形式
    getWord() {
        var str = [];
        for (var i = 65; i < 91; i++) {
            str.push(String.fromCharCode(i));
        }
        return str;
    },
    //判断系统是否是安卓或者ios
    judgeSystem() {
        var u = navigator.userAgent, app = navigator.appVersion;
        var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //g
        var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        if (isAndroid) {
            //这个是安卓操作系统
            return 'isAndroid'
        }
        if (isIOS) {
            //这个是ios操作系统
            return 'isIOS'
        }
    },
    //是否微信的判断
    isWeChat() {
        let ua = navigator.userAgent.toLowerCase();
        return ua.match(/MicroMessenger/i) == "micromessenger";
    },
    // 唤起app(应用市场)
    openAapp() {
        if (this.isWeChat()) {
            window.location.href = "https://a.app.qq.com/o/simple.jsp?pkgname=com.chtwm.mall&fromcase=40002";
        } else {
            if (this.judgeSystem() == 'isAndroid') {
                window.location.href = "htjf11://jump11";
                setTimeout(() => {
                    window.location.href =
                        "https://a.app.qq.com/o/simple.jsp?pkgname=com.chtwm.mall&fromcase=40002";
                }, 2000);
            }
            if (this.judgeSystem() == 'isIOS') {
                window.location.href = "htjf://jump";
                setTimeout(() => {
                    window.location.href =
                        "https://a.app.qq.com/o/simple.jsp?pkgname=com.chtwm.mall&fromcase=40002";
                }, 2000);
            }
        }
    },
    // 进入app指定页面
    openAssignPage(url, time) {
        let timeoutTime = time ? time : 2000;
        if (this.isWeChat()) {
            window.location.href = "https://a.app.qq.com/o/simple.jsp?pkgname=com.chtwm.mall&fromcase=40002";
        } else {
            if (this.judgeSystem() == 'isAndroid') {
                let urlSign = (url.indexOf('?') == -1) ? '?' : '&';
                window.location.href = `intent://${url}${urlSign}type=1&#Intent;scheme=safe8c02aa;launchFlags=0x10000000;end`;
                setTimeout(() => {
                    window.location.href =
                        "https://a.app.qq.com/o/simple.jsp?pkgname=com.chtwm.mall&fromcase=40002";
                }, timeoutTime);
            }
            if (this.judgeSystem() == 'isIOS') {
                window.location.href = "htjf://jump/com/commenWeb?url=" + url;
                setTimeout(() => {
                    window.location.href =
                        "https://a.app.qq.com/o/simple.jsp?pkgname=com.chtwm.mall&fromcase=40002";
                }, timeoutTime);
            }
        }
    },
    // 隐藏骨架屏
    hideSkeleton() {
        let deviceType = this.judgeSystem();
        if (deviceType == 'isAndroid') {
            window.jsObj && window.jsObj.hideSkeleton();
        } else if (deviceType == 'isIOS') {
            window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.hideSkeleton.postMessage('hideSkeleton');
        }
    },
    // 展示隐藏原生底部导航栏
    showTabbar(isShow) {
        let deviceType = this.judgeSystem();
        let isShowObj = { show: isShow };
        if (deviceType == 'isAndroid') {
            window.jsObj && window.jsObj.showTabbar(JSON.stringify(isShowObj));
        } else if (deviceType == 'isIOS') {
            window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.showTabbar.postMessage(JSON.stringify(isShowObj));
        }
    },
    //比较时间前后
    compareDate(date1, date2) {
        var oDate1 = date1 && new Date(date1);
        var oDate2 = date2 && new Date(date2);
        if (oDate1.getTime() > oDate2.getTime()) {
            return true
        } else {
            return false
        }

    },
    // 处理历史业绩的业绩排名情况
    stringMani(str1, str2) {
        var str = str1.indexOf(str2);
        return str1.substring(0, str);
    },
    stringMani2(str1, str2) {
        var str = str1.indexOf(str2);
        return str1.substring(str + 1, str1.length);
    },
    wxShare(obj) {
        let deviceType = this.judgeSystem();
        if (deviceType == 'isAndroid') {
            window.jsObj && window.jsObj.wxShare(JSON.stringify(obj));
        } else if (deviceType == 'isIOS') {
            window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.wxShare.postMessage(JSON.stringify(obj));
        }
    },

    //兼容获取地址参数
    getParams(that, key) {
        if (getVarType.isArray(that.$route.query[key])) {
            return that.$route.query[key][0] ? that.$route.query[key][0] : (splitUrl()[key] ? splitUrl()[key] : '')
        } else {
            return that.$route.query[key] ? that.$route.query[key] : (splitUrl()[key] ? splitUrl()[key] : '')
        }
    },

    // 是否是新包
    // isNewAppPackage(newVersion) {
    //     let myVersion = store.state.appVersion;
    //     let myVersionNum = myVersion?Number(myVersion.replace(/\./g, '')):0;
    //     let newVersionNum = newVersion?Number(newVersion.replace(/\./g, '')):0;
    //     // 新包
    //     if(myVersionNum >= newVersionNum) {
    //         return true;
    //     } else {
    //         return false;
    //     }
    // },
    isNewAppPackage(newVersion) {
        var myVersion = store.state.appVersion;
        var myVersion_array = myVersion.split(".");
        var newVersion_array = newVersion.split(".");
        var is_upgrade = true;
        if (newVersion_array.length == 3 && myVersion_array.length == 3) {
            for (var i = 0; i < newVersion_array.length; i++) {
                if (parseInt(newVersion_array[i]) < parseInt(myVersion_array[i])) {
                    is_upgrade = true;
                    break;
                }
                else {
                    if (parseInt(newVersion_array[i]) == parseInt(myVersion_array[i])) {
                        continue;
                    }
                    else {
                        is_upgrade = false;
                        break;
                    }
                }
            };
        }
        return is_upgrade;
    },
    // 下载pdf
    downloadNew(fileUrl, fileName, groupName, show) {
        // show 1代表在线展示，不传此参数表示下载
        if (show) {
            return httpConfig.downloadNew_api + "?filePath=" + fileUrl + "&fileName=" + fileName + "&groupName=" + groupName + "&show=" + show;
        }
        else {
            return httpConfig.downloadNew_api + "?filePath=" + fileUrl + "&fileName=" + fileName + "&groupName=" + groupName + "&show=1";
        }
    },
    // 初始化微信sdk
    initWX(paramUrl, title, desc, link, imgUrl) {
        if (this.isWeChat()) {
            _axiosHttp.http({
                url: httpConfig.share_api,
                data: {
                    url: paramUrl
                }
            }, (res) => {
                let data = res.data;
                wx.config({
                    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    appId: data.appid, // 必填，企业号的唯一标识，此处填写企业号corpid
                    timestamp: data.timestamp, // 必填，生成签名的时间戳
                    nonceStr: data.nonceStr, // 必填，生成签名的随机串
                    signature: data.signature,// 必填，签名，见附录1
                    jsApiList: ['hideMenuItems', 'showMenuItems', 'onMenuShareAppMessage', 'onMenuShareTimeline']
                });
                // 分享到微信好友
                wx.onMenuShareAppMessage({
                    title,
                    desc, // 分享描述
                    link,
                    imgUrl,
                    success: function () { }
                });
                //分享到朋友圈
                wx.onMenuShareTimeline({
                    title, // 分享标题
                    link, // 分享链接
                    imgUrl, // 分享图标
                    success: function () { },
                    cancel: function () { }
                });
            },
                (res) => {

                },
                (res) => {

                });
        }
    },
}
export default utils
